from flask import Blueprint, request, jsonify
from werkzeug.exceptions import BadRequest
from app import db
from app.categories.models import Category
from app.categories.schemas import category_schema, categories_schema, category_simple_schema, categories_simple_schema

# 创建分类模块的蓝图
categories_bp = Blueprint('categories', __name__)

@categories_bp.route('', methods=['GET'])
def get_categories():
    """
    获取所有分类列表
    ---
    响应：分类列表
    """
    categories = Category.query.all()
    return jsonify(categories_schema.dump(categories))

@categories_bp.route('/<int:category_id>', methods=['GET'])
def get_category(category_id):
    """
    获取单个分类的详细信息
    ---
    参数：category_id - 分类ID
    响应：分类详细信息
    """
    category = Category.query.get_or_404(category_id)
    return jsonify(category_schema.dump(category))

@categories_bp.route('', methods=['POST'])
def create_category():
    """
    创建新分类
    ---
    请求体：分类信息
    响应：创建成功的分类信息
    """
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 验证必填字段
    if 'name' not in data:
        raise BadRequest('Missing required field: name')
    
    # 检查分类名称是否已存在
    if Category.query.filter_by(name=data['name']).first():
        raise BadRequest('Category name already exists')
    
    # 创建分类对象
    category = Category(
        name=data['name'],
        description=data.get('description'),
        parent_id=data.get('parent_id')
    )
    
    db.session.add(category)
    db.session.commit()
    
    return jsonify(category_schema.dump(category)), 201

@categories_bp.route('/<int:category_id>', methods=['PUT'])
def update_category(category_id):
    """
    更新分类信息
    ---
    参数：category_id - 分类ID
    请求体：更新的分类信息
    响应：更新后的分类信息
    """
    category = Category.query.get_or_404(category_id)
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 检查是否更新了名称，如果更新了则检查唯一性
    if 'name' in data and data['name'] != category.name:
        if Category.query.filter_by(name=data['name']).first():
            raise BadRequest('Category name already exists')
        category.name = data['name']
    
    # 更新其他字段
    if 'description' in data: category.description = data['description']
    if 'parent_id' in data: 
        # 检查父分类是否存在
        if data['parent_id'] is not None:
            parent_category = Category.query.get(data['parent_id'])
            if not parent_category:
                raise BadRequest(f'Parent category not found: {data["parent_id"]}')
        category.parent_id = data['parent_id']
    
    db.session.commit()
    
    return jsonify(category_schema.dump(category))

@categories_bp.route('/<int:category_id>', methods=['DELETE'])
def delete_category(category_id):
    """
    删除分类
    ---
    参数：category_id - 分类ID
    响应：成功删除的消息
    """
    category = Category.query.get_or_404(category_id)
    
    # 检查是否有子分类
    if category.children:
        raise BadRequest('Cannot delete category with subcategories')
    
    db.session.delete(category)
    db.session.commit()
    
    return jsonify({'message': 'Category deleted successfully'})

@categories_bp.route('/roots', methods=['GET'])
def get_root_categories():
    """
    获取根分类（没有父分类的分类）
    ---
    响应：根分类列表
    """
    categories = Category.query.filter_by(parent_id=None).all()
    return jsonify(categories_schema.dump(categories))

@categories_bp.route('/<int:category_id>/children', methods=['GET'])
def get_category_children(category_id):
    """
    获取指定分类的子分类
    ---
    参数：category_id - 分类ID
    响应：子分类列表
    """
    category = Category.query.get_or_404(category_id)
    return jsonify(categories_schema.dump(category.children))